
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Web;

namespace MediaCache
{
	/// <summary>
	/// Needed by ASP.NET to create HttpHandler objects for requests mapped to a given http handler.
    /// The MediaCache library uses this to provide the ImageRequestHandler class in this same package.
	/// </summary>
	public class ImageRequestHandlerFactory : IHttpHandlerFactory
	{
		protected static IDictionary m_handlers = new Hashtable();
        protected static string s_mediaCacheNamePrefix;
		public ImageRequestHandlerFactory()
		{
            s_mediaCacheNamePrefix = Swaf.Application.globalApp.appData["MediaCacheNamePrefix"].ToString();
		}
		#region IHttpHandlerFactory Members
        /// <summary>
        /// 
        /// </summary>
        /// <param name="handler"></param>
		public void ReleaseHandler(IHttpHandler handler)
		{
			// TODO:  Add ImageRequestHandlerFactory.ReleaseHandler implementation
		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requestType"></param>
        /// <param name="url"></param>
        /// <param name="pathTranslated"></param>
        /// <returns></returns>
		public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
		{
			string catalogName = getCatalogName(url, context);
			IHttpHandler handler = (IHttpHandler)m_handlers[catalogName];
			if(handler == null)
				m_handlers[catalogName] = handler = new ImageRequestHandler(catalogName);
		
			return handler;
		}

		#endregion
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="context"></param>
        /// <returns></returns>
		protected string getCatalogName(string name, HttpContext context)
		{
			string baseName = context.Request.ApplicationPath;
			string subName = name.Substring(baseName.Length + (baseName == "/"?0:1));
			int pos = subName.IndexOf(s_mediaCacheNamePrefix);
            if (pos != -1)
                subName = subName.Substring(pos + s_mediaCacheNamePrefix.Length);
            pos = subName.IndexOf('/');
            if (pos != -1)
            {
                subName = subName.Substring(0, pos);
                return subName;
            }
			return null;
		}
	}
}
